/**
 * 
 */
package org.gigi.security.repository.hibernate;

import java.util.List;

import org.gigi.security.domain.Menu;
import org.gigi.security.repository.MenuRepository;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

/**
 * 菜单持久层类。
 *
 * @author Eugene Wang 2011-9-13
 * @see
 */
@Repository
public class HibernateMenuRepository extends AbstractHibernateRepository
		implements MenuRepository {

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#create(org.gigi.security.domain.Menu)
	 */
	@Override
	public void create(Menu menu) {
		getSession().save(menu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#findByCode(java.lang.String)
	 */
	@Override
	public Menu findByCode(String code) {
		return (Menu) getSession().get(Menu.class, code);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#delete(org.gigi.security.domain.Menu)
	 */
	@Override
	public void delete(Menu menu) {
		menu.setAuthority(null);
		getSession().delete(menu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#update(org.gigi.security.domain.Menu)
	 */
	@Override
	public void update(Menu menu) {
		getSession().update(menu);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#findAll()
	 */

	@Override
	@SuppressWarnings("unchecked")
	public List<Menu> findChildren(String parentCode) {
		String hql = "from Menu m WHERE m.parent.code = :parentCode ORDER BY m.layerOrder ASC";
		if ((parentCode == null) || Menu.ROOT_CODE.equals(parentCode)) {
			hql = "from Menu m WHERE m.parent.code IS NULL ORDER BY m.layerOrder ASC";
		}
		Query query = getSession().createQuery(hql);
		if ((parentCode != null) && !Menu.ROOT_CODE.equals(parentCode)) {
			query.setParameter("parentCode", parentCode);
		}
		return query.list();
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.MenuRepository#findAll()
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<Menu> findAll() {
		String hql = "from Menu m ";
		Query query = getSession().createQuery(hql);
		return query.list();
	}
	
}
